//
//  DataService.m
//  12580coupon
//
//  Created by tanghe on 15/1/2.
//  Copyright (c) 2015年 lanerkeji. All rights reserved.
//

#import "DataService.h"
#import "NSIDchangeType.h"
#import "AppDelegate.h"

#import <netdb.h>
#import <arpa/inet.h>


@implementation DataService
 
+ (BOOL)userinfo
{
    //UIPageControl
    
    
    NSUserDefaults *defalut=[NSUserDefaults standardUserDefaults];
    NSString *i=(NSString*)[defalut objectForKey:@"Userinfo"];
    
    return i?YES:NO;
    //    return YES;
}
+(NSDictionary *) GetUnameInfo{
    NSUserDefaults *defalut=[NSUserDefaults standardUserDefaults];
    NSDictionary *i=(NSDictionary*)[defalut objectForKey:@"Userinfo"];
    return i;
}
/**
 * 判断是否有网络
 * @return 网络状态
 * @throws Exception
 */
+(BOOL) isConnectionAvailable
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);

    if (isReachable && !needsConnection) {
        return YES;
    }

    return NO;
}

-(void)CheckConnection:(NSNotification *)notification
{
    // Create zero addy
}

#pragma mark 总请求
+(void)jtyRequest:(id)params routeUrl:(NSString *)routeUrl requestType:(NSString *)requestType SuccsessBlock:(SuccsessBlock)succsessBlock failureBlock:(FailureBlock)failureBlock
{
    if (![DataService isConnectionAvailable]) {
        [DataService statecode:100];
        return;
    }

    NSString *urlqe = BASE_URL;
    
    NSString *url=[NSString stringWithFormat:@"%@%@",urlqe,routeUrl];
    [self apiRequestCopy:url parameters:params];
    url =  [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
   
    NSLog(@"%@\n\tparams=%@",url,params);
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.requestSerializer.timeoutInterval = 10;
    session.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
  

//    [session.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    
    if ([routeUrl isEqualToString:@"/system/user/resetPwdphone"]){
        [session.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    }
//    [session.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    if ([requestType isEqualToString:@"GET"]) {
        [session GET:url parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            failureBlock([NSString stringWithFormat:@"请求失败"]);
            failureBlock(error.localizedDescription);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }else if ([requestType isEqualToString:@"PUT"]){
        [session PUT:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
//            [DataService MsgBodayCount:responseObject urlstring:url];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }else if ([requestType isEqualToString:@"DELETE"]){
        [session DELETE:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }
    else{
        [session POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }
  
}

/*
 * 网络请求
 * params：请求参数
 * routeUrl:url路径
 * requestType:请求类型（如：POST、GET）
 * SuccsessBlock：请求完成之后回调的block
 */
+(void)jtyRequest:(id)params
        routeUrl:(NSString *)routeUrl
     requestType:(NSString *)requestType
          header:(NSDictionary *)header
   SuccsessBlock:(SuccsessBlock)succsessBlock
    failureBlock:(FailureBlock)failureBlock{
    if (![DataService isConnectionAvailable]) {
        [DataService statecode:100];
        return;
    }

    NSString *urlqe = BASE_URL;
    if ([routeUrl isEqualToString:@"/cjb/sendSmsCode"] || [routeUrl isEqualToString:@"/cjb/path/send"]  ){
        urlqe = BaseAPI2;
    }
    NSString *url=[NSString stringWithFormat:@"%@%@",urlqe,routeUrl];
    [self apiRequestCopy:url parameters:params];
    url =  [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
   
    NSLog(@"%@\n\tparams=%@",url,params);
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.requestSerializer.timeoutInterval = 10;
    session.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
    for (NSString *value in header.allKeys) {
        [session.requestSerializer setValue:header[value] forHTTPHeaderField:value];
    }

    [session.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    if ([routeUrl isEqualToString:@"/system/user/resetPwdphone"]){
        [session.requestSerializer setValue:nil forHTTPHeaderField:@"Authorization"];
    }
//    [session.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    if ([requestType isEqualToString:@"GET"]) {
        [session GET:url parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            failureBlock([NSString stringWithFormat:@"请求失败"]);
            failureBlock(error.localizedDescription);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }else if ([requestType isEqualToString:@"PUT"]){
        [session PUT:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
//            [DataService MsgBodayCount:responseObject urlstring:url];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }else if ([requestType isEqualToString:@"DELETE"]){
        [session DELETE:url parameters:params headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }
    else{
        [session POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          
            NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
            responseObject=[idchangeType changeTypes:responseObject];
            
            succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            failureBlock([NSString stringWithFormat:@"请求失败"]);
            NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
            [DataService statecode:(long)urlResponse.statusCode];
        }];
    }
}


+(NSDictionary *)MsgBodayCount:(id)responseObject urlstring:(NSString *)url{
    
    NSDictionary *responeDic;
        NSData *responeData;
        if ([responseObject isKindOfClass:[NSString class]]) {
            responeData = [responseObject dataUsingEncoding:NSUTF8StringEncoding];
        }else if ([responseObject isKindOfClass:[NSData class]]) {
            responeData = responseObject;
            NSString *resStr = [[NSString alloc]initWithData:responeData encoding:NSUTF8StringEncoding];
            NSLog(@"返回数据:url%@ %@\n",url,resStr);
        }else if ([responseObject isKindOfClass:[NSDictionary class]]){
            responeDic = [responseObject mutableCopy];
            NSLog(@"返回数据:%@ %@\n",url,responeDic);
        }
        if (!responeDic && !responeData) {
//            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"返回数据是空"                                                                      forKey:NSLocalizedDescriptionKey];
//            NSError *aError = [NSError errorWithDomain:@"" code:0 userInfo:userInfo];
            //返回错误信息
    //        BLOCK_EXEC(failure,aError);
            return [NSDictionary dictionary];
        }
        NSError *error;
        if (!responeDic) {
            responeDic = [NSJSONSerialization JSONObjectWithData:responeData options:0 error:&error];
        }
        
        if (error) {
            if ([responseObject isKindOfClass:[NSString class]]) {
    //            BLOCK_EXEC(success,respone);
            }else{
//                NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"请求数据失败"                                                                      forKey:NSLocalizedDescriptionKey];
//                NSError *aError = [NSError errorWithDomain:@"" code:0 userInfo:userInfo];
                //返回处理信息
    //            BLOCK_EXEC(failure,aError);
            }
        }else if(responeDic){
            if ([[responeDic objectForKey:@"code"] intValue] == 401) {
                //认证失败 退出登录
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserModel"];
                
            }else if ([[responeDic objectForKey:@"code"] intValue] == 20001) {
               
            }
            return responeDic;
        }
        return [NSDictionary dictionary];
//    NSLog(@"%@==%@",url,jsonStr);
}
+ (void)PUTWithURLStr:(NSString *)urlStr
             filePath:(NSDictionary *)filePath
    SuccsessBlock:(SuccsessBlock)succsessBlock failureBlock:(FailureBlock)failureBlock{
    
    // 1. url 最后一个是要上传的文件名
    
    
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,urlStr]];
    
    // 2. request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"PUT";
    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
 
 
    NSMutableData  * postData =[NSMutableData dataWithCapacity:512];
    
    for (int i =0; i<[filePath count]; i++) {
      
        [postData  appendData: [[NSString  stringWithFormat:@"%@=%@",[[filePath allKeys] objectAtIndex:i],[filePath objectForKey:[[filePath allKeys] objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]];
        
    }
    
 
    request.HTTPBody = postData;
    // 4. 由session发起任务
 
  [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    

        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"sesult---> %@ %@", result, [NSThread currentThread]);

        if (!error) {
            succsessBlock(result);
        }else{
            failureBlock(error.localizedDescription);
        }

    }] resume];
    
}
+(NSString *)qulistQingqiu:(NSDictionary *)keyDic{
//    [postData  appendData: [[NSString  stringWithFormat:@"%@=%@",[[filePath allKeys] objectAtIndex:i],[filePath objectForKey:[[filePath allKeys] objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]]
    NSString *urlString = @"";
    for (int i = 0; i<keyDic.count; i++) {
        NSString *keyString = [NSString  stringWithFormat:@"%@=%@",[[keyDic allKeys] objectAtIndex:i],[keyDic objectForKey:[[keyDic allKeys] objectAtIndex:i]]];
        if (i==0) {
            urlString = [NSString stringWithFormat:@"%@",keyString];
        }else{
            urlString = [NSString stringWithFormat:@"%@&%@",urlString,keyString];
        }
    }
    
    return urlString;
}


+(void)statecode:(NSInteger)code{
    //  阿 倌 忙不过来了，如您正在进行
    // 资金类交易，谓播认交易是否成
    // 功，以免璗a 操作，
    // <1)谓您釅认是否已开启手机银行
    // 网络使用权限；
    // <2>谓您切換手机移动网络或通过
    // 切換飞行模式重新连接网络后鬣
    // 试：
    // (3)如网络问埋仍未解决，您可尝
    // 试轚启手机，
    NSString * stringtishi =@"亲，点慢点，网络都跟不上你的节奏了";
    if (code == 100) {
        stringtishi =@"亲，请确保您的手机可以正常使用网络。";
    }else{
        return;;
    }
  
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:stringtishi preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //
        //        [DataService tiaozhuanssss:code];
        //        [[NSUserDefaults standardUserDefaults]    removeObjectForKey:@"Userinfo"];
        //
        //        [[NSUserDefaults standardUserDefaults]   synchronize];
        
    }];
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.alignment = NSTextAlignmentLeft;
    NSMutableAttributedString *atrStr = [[NSMutableAttributedString alloc] initWithString:stringtishi attributes:@{NSParagraphStyleAttributeName:paraStyle,NSFontAttributeName:[UIFont systemFontOfSize:14.0]}];
//    [atrStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0,stringtishi.length)];
 
    [alertController setValue:atrStr forKey:@"attributedMessage"];
    [alertController addAction:okAction];
    
    UIViewController *currentVC = [DataService getCurrentVC];
    
    [currentVC presentViewController:alertController animated:YES completion:nil];
    
}
+(void)tiaozhuanssss:(NSInteger)code{
    
    UIStoryboard *storybordMore = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *currentVC = [DataService getCurrentVC];
    currentVC.hidesBottomBarWhenPushed = YES;
    
    if ([NSStringFromClass([currentVC class]) isEqualToString:@"ViewController"]){
        
    }else{
        [currentVC.navigationController pushViewController:[storybordMore instantiateViewControllerWithIdentifier:[NSString stringWithFormat:@"ViewControllerID"]] animated:YES];
    }
    
    
}

//userinfo  储存用户信息
-(void)appUserDefaults:(NSDictionary *)dic key:(NSString *)key{
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:key];
}
-(NSDictionary *)appUserDefaults:(NSString *)key{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    return [user objectForKey:key];
}
+(void)yfPhotoRequest:(NSDictionary *)params imageArray:(NSArray *)imageArrays routeUrl:(NSString *)routeUrl flie:(NSString *)flie SuccsessBlock:(SuccsessBlock)succsessBlock failureBlock:(FailureBlock)failureBlock{
    
    NSString *urlqe = BASE_URL;
    NSString *url=[NSString stringWithFormat:@"%@%@",urlqe,routeUrl];//放上传图片的网址
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.responseSerializer = [AFHTTPResponseSerializer serializer];//设置服务器允许的请求格式内容
//    session.requestSerializer = [AFJSONRequestSerializer serializer];
//    session.responseSerializer.acceptableContentTypes = [NSSet   setWithObjects:@"text/html", @"text/json", nil];
//    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //上传图片/文字，只能同POST
    
    
    
    [session POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i =0; i<[imageArrays count]; i++) {
            NSLog(@"leixin = %@",flie);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

            formatter.dateFormat = @"yyyyMMddHH:mm";
            NSInteger ss = arc4random();
            NSString *time = [formatter stringFromDate:[NSDate date]];
 
            
            NSString *fileName = [NSString stringWithFormat:@"%@%ld.jpg", time,(long)ss];
            [formData appendPartWithFileData:[imageArrays objectAtIndex:i] name:flie fileName:fileName mimeType:@"image/jpeg"];
        }
        session.requestSerializer.timeoutInterval = 15;
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress = %@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        //获得的json先转换成字符串
        NSIDchangeType *idchangeType= [[NSIDchangeType alloc] init];
        responseObject=[idchangeType changeTypes:responseObject];
        
        succsessBlock([DataService MsgBodayCount:responseObject urlstring:url]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         failureBlock((NSString *)error);
    }];
}
//-(void)
/**
 复制错误信息
 */
+ (void)apiRequestCopy:(NSString *)url parameters:(NSDictionary *)parameters{
    NSString *bUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *errorStr = [NSString stringWithFormat:@"url:%@\nparams:%@",bUrl,parameters];
    [self pasteboard:errorStr];
}
+ (void)apiErrorCopy:(NSString *)url parameters:(NSDictionary *)parameters errorRespone:(NSString *)errorRespone
{
    //DEBUG模式下请求错误拷贝错误到粘贴板
    NSString *bUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *errorStr = [NSString stringWithFormat:@"异常接口!!!\nurl:%@\nparams:%@\n请求框架错误信息反馈:%@",bUrl,parameters,errorRespone];
    [self pasteboard:errorStr];
}
+ (void)httpCodeErrorRuternRespone:(NSString *)url parameters:(NSDictionary *)parameters errorRespone:(NSString *)errorRespone{
    NSString *bUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *errorStr = [NSString stringWithFormat:@"异常接口!!!\nurl:%@\nparams:%@\n接口回馈:%@",bUrl,parameters,errorRespone];
    [self pasteboard:errorStr];
}
+ (void)pasteboard:(NSString *)errorStr{
    NSDictionary *debugDic = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NetworkIsDebug" ofType:@"plist"]];
    BOOL isDebugging = [debugDic[@"isDebugging"] boolValue];
    if (isDebugging) {
        UIPasteboard *pboard = [UIPasteboard generalPasteboard];
        pboard.string = errorStr;
    }
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [DataService getCurrentVCFrom:rootViewController];
    return currentVC;
}
+(UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
 
    if ([rootVC presentedViewController]) {
 
        rootVC = [rootVC presentedViewController];

    }
 
    if ([rootVC isKindOfClass:[UITabBarController class]]) {

        // 根视图为UITabBarController
 
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
 
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){

        // 根视图为UINavigationController
 
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
 
    } else {

        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;

}

@end
